﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.Cultivation;
using Tb.App.Domain.Rabbit.Cultivation;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.Cultivation
{
    /// <summary>
    /// 添加养殖企业-命令
    /// </summary>
    public class AddCultivationCommpanyCommandHandler : IRequestHandler<AddCultivationCommpanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CultivationCommpanyModel> commpanyRep;
        private readonly IMapper mapper;

        public AddCultivationCommpanyCommandHandler(IBaseRepository<CultivationCommpanyModel> commpanyRep,IMapper mapper,ILogger<AddCultivationCommpanyCommandHandler> logger)
        {
            this.commpanyRep = commpanyRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddCultivationCommpanyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            // 获取数据库的执行策略
            var executionStrategy = commpanyRep.DB.Database.CreateExecutionStrategy();
            // 使用执行策略执行事务操作
            await executionStrategy.ExecuteAsync(async () =>
            {
                using (var tran = await commpanyRep.DB.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {

                        var info=commpanyRep.GetAll().Where(x=>!x.IsDel&&x.Batch==request.Batch).ToList();
                        info.ForEach(o =>
                        {
                            o.IsDel=true;
                        });
                        await commpanyRep.UpdateRange(info);

                        var entity = mapper.Map<CultivationCommpanyModel>(request);
                        int a = await commpanyRep.AddAsync(entity);
                        if (a > 0)
                        {
                            result.Code = ApiEnum.添加成功;
                            result.Message = ApiEnum.添加成功.ToString() + ":养殖企业信息";
                            result.Data = a;
                        }
                        else
                        {
                            result.Code = ApiEnum.添加失败;
                            result.Message = ApiEnum.添加失败.ToString() + ":养殖企业信息";
                            result.Data = a;
                        }

                        await tran.CommitAsync(cancellationToken);
                    }
                    catch (Exception)
                    {
                        result.Code = ApiEnum.添加失败;
                        result.Message = ApiEnum.添加失败.ToString() + ":养殖企业信息";
                        await tran.RollbackAsync(cancellationToken);
                        throw;
                    }
                }
            });
              
            return result;
        }
    }
}
